package city.spring.modules.work.service.impl;

import city.spring.modules.work.entity.WorkPlanEntity;
import city.spring.modules.work.repository.WorkPlanRepository;
import city.spring.modules.work.repository.WorkPlanShiftExtRepository;
import city.spring.modules.work.repository.WorkPlanUserExtRepository;
import city.spring.modules.work.service.WorkPlanService;
import city.spring.modules.work.service.WorkPlanShiftExtService;
import city.spring.modules.work.service.WorkPlanUserExtService;
import city.spring.modules.work.vo.WorkPlanVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Service：排班方案（上班方案）
 *
 * @author 侯坤林
 * @date 2020-06-04 16:43:43
 */
@CacheConfig(cacheNames = {WorkPlanServiceImpl.CACHE_NAME})
@Transactional(rollbackFor = Throwable.class)
@Service
public class WorkPlanServiceImpl extends ServiceImpl<WorkPlanRepository, WorkPlanEntity> implements WorkPlanService {

    private final WorkPlanShiftExtService planShiftExtService;
    private final WorkPlanShiftExtRepository planShiftExtRepository;

    private final WorkPlanUserExtService planUserExtService;
    private final WorkPlanUserExtRepository planUserExtRepository;

    public WorkPlanServiceImpl(WorkPlanShiftExtService planShiftExtService, WorkPlanUserExtService planUserExtService) {
        this.planShiftExtService = planShiftExtService;
        this.planShiftExtRepository = (WorkPlanShiftExtRepository) planShiftExtService.getBaseMapper();
        this.planUserExtService = planUserExtService;
        this.planUserExtRepository = (WorkPlanUserExtRepository) planUserExtService.getBaseMapper();
    }

    @Override
    public WorkPlanVO getWorkPlan(String id) {
        WorkPlanEntity planEntity = getById(id);
        WorkPlanVO planVO = new WorkPlanVO(planEntity);
        // 加载排班计划的上班班次列表
        planVO.setShifts(planShiftExtRepository.getPlanShifts(id));
        // 加载排班计划的用户列表
        planVO.setUsers(planUserExtRepository.getPlanUsers(id));

        return planVO;
    }

    @Override
    public void saveWorkPlan(WorkPlanEntity entity) {
        if (!save(entity)) {
            throw new RuntimeException("保存信息失败");
        }
    }

    @Override
    public void updateWorkPlan(WorkPlanEntity entity) {
        // 使用 updateById(entity); 修改数据时，将会修改 entity 对象中所有非null数据，如果某个字段为null，将会忽略该字段的修改
        boolean update = updateById(entity);
        if (!update) {
            throw new RuntimeException("修改信息失败");
        }
    }

    @Override
    public void deleteWorkPlan(String primaryKey) {
        removeById(primaryKey);
    }

    @Override
    public void deleteWorkPlan(List<String> primaryKeys) {
        removeByIds(primaryKeys);
    }
}